package cn.org.donald.sensitive.util;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author Donald
 * @since 2023-11-16 15:32:42
 **/
public class StringUtil {
    public static String replaceTargetToStar(String input, String regex) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);
        List<String> targetStringList = new ArrayList<>();
        while (matcher.find()) {
            targetStringList.add(matcher.group());
        }
        List<String> collect = targetStringList.stream().sorted(Comparator.comparingInt(String::length).reversed()).collect(Collectors.toList());
        for (String s : collect) {
            @SuppressWarnings(value = "all")
            String replacement = s.replaceAll(".", "*");
            input = input.replace(s, replacement);
        }
        return input;
    }
}
